package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryOrder;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.mapper.*;
import com.itheima.pojo.*;
import com.itheima.service.OrderSettingListService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 预约管理业务层
 */

@Service(interfaceClass = OrderSettingListService.class)
@Transactional
public class OrderSettingListServiceImpl implements OrderSettingListService {
    @Autowired
    private OrderSettingListMapper orderSettingListMapper;
    @Autowired
    private SetMealMapper setMealMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderSettingMapper orderSettingMapper;

    /**
     * 分页条件查询
     */
    @Override
    public PageResult findPage(QueryOrder queryOrder) throws Exception {
        Integer currentPage = queryOrder.getCurrentPage();//当前页
        Integer pageSize = queryOrder.getPageSize();//每页显示条目数


        List<Date> orderDate = queryOrder.getOrderDate();

        if (orderDate != null && orderDate.size() > 0) {
            if (orderDate.get(0) != null) {
                Date start = orderDate.get(0);
                String sDate = DateUtils.parseDate2String(start);
                queryOrder.setStartDate(sDate);//起始时间
            }
            if (orderDate.get(1) != null) {
                Date end = orderDate.get(1);
                String eDate = DateUtils.parseDate2String(end);
                queryOrder.setEndDate(eDate);//结束时间
            }
        }
        //使用分页插件
        PageHelper.startPage(currentPage, pageSize);
        Page<Order> orders = orderSettingListMapper.selectByCondition(queryOrder);
        long total = orders.getTotal();
        List<Order> result = orders.getResult();
        for (Order order : result) {
            Address address =  orderSettingListMapper.findAddressByOrderId(order.getId());
            order.setAddress(address);
        }
        return new PageResult(total, result);
    }

    /**
     * 编辑预约状态
     */
    @Override
    public void changeStatus(Map map) {
        orderSettingListMapper.changeStatus(map);
    }

    /**
     * 查询所有套餐
     */
    @Override
    public List<Setmeal> findAll() {
        return setMealMapper.getAllSetmeal();
    }

    /**
     * 添加预约
     */
    @Override
    public Result add(Map map) throws Exception {
        //1.检查是否能够预约
        String date = (String) map.get("orderDate");   //获取日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String orderDate = sdf.format(sdf.parse(date));
        OrderSetting orderSetting = orderMapper.findByOrderDate(orderDate);
        if (orderSetting == null) {
            //指定日期无法进行预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2.检查是否约满了
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (reservations >= number) {
            //预约满了
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //3. 检查预约的用户是否重复预约 (当天同一个套餐预约)
        Member member = memberMapper.findByTelephone((String) map.get("phoneNumber"));
        //用户是否存在
        if (member != null) {
            //如果存在,判断是否重复预约
            Order order = new Order();
//            order.setMemberId(member.getId());
            Integer member_id = member.getId();
            order.setMemberId(member_id);
            order.setOrderDate(DateUtils.parseString2Date(orderDate));
            order.setSetmealId(Integer.parseInt((String) map.get("setmealIds")));

//            System.out.println(order);

            List<Order> list = orderMapper.findByCondition(order);
            if (list != null && list.size() > 0) {
                //当天存在重复预约 返回失败
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
            //判断当天预约是否等于2(最多预约两次)
            Map<String, Object> nameAndDate = new HashMap<>();
            nameAndDate.put("member_id", member_id);
            nameAndDate.put("orderDate", orderDate);
            int orderNumber = orderSettingListMapper.findOrderCountByNameAndDate(nameAndDate);
            if (orderNumber == 2) {
                return new Result(false, "当天最多预约两个套餐");
            }
        } else {
            //用户不存在 创建用户
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber((String) map.get("phoneNumber"));
            member.setRegTime(new Date());
            memberMapper.add(member);//注册会员
        }
        //预约成功 保存到数据库
        //查询address
        String addressId = (String) map.get("addressIds");
        Integer addressIds = Integer.parseInt(addressId);
        Address address = orderSettingListMapper.findAddressById(addressIds);

        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(DateUtils.parseString2Date(orderDate));
        order.setOrderType(order.ORDERTYPE_TELEPHONE); //预约类型:电话预约
        order.setOrderStatus(Order.ORDERSTATUS_NO); //预约状态:未到诊
        order.setSetmealId(Integer.parseInt((String) map.get("setmealIds")));//添加套餐
        order.setAddress(address);//地址信息
        orderMapper.add(order);     //添加预约信息
        Integer order_id = order.getId();
        //map1 存放order_id address_id
        Map map1 = new HashMap();
        map1.put("order_id", order_id);
        map1.put("address_id", addressIds);
        //添加关联表信息
        orderSettingListMapper.addAddressAssociation(map1);

        //设置已预约人数+1
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingMapper.editReservations(orderSetting);
        //预约成功 发送短信
//        SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,(String) map.get("telephone"),"success");
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    /**
     * 根据ID查询
     */
    @Override
    public List<Integer> findById(int id) {
        return orderSettingListMapper.findById(id);
    }

    /**
     * 编辑
     */
    @Override
    public void edit(Map map) throws Exception {
        Map map1 = (Map) map.get("member");//member数据
        String name = (String) map.get("name");
        Integer memberId = (Integer) map.get("memberId");
        Member member = new Member();
        member.setId(memberId);
        member.setName(name);
        memberMapper.edit(member);//编辑member


        String date = (String) map.get("orderDate");   //获取日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String orderDate = sdf.format(sdf.parse(date));
        String orderStatus = (String) map.get("orderStatus");//预约状态
        String orderType = (String) map.get("orderType");//预约类型
        String ids = (String) map.get("setmealIds");
        Integer setmealIds = Integer.parseInt(ids);//预约套餐的ID
        Integer id = (Integer) map.get("id");

        //查询address
        String addressId = (String) map.get("addressIds");
        Integer addressIds = Integer.parseInt(addressId);
        Address address = orderSettingListMapper.findAddressById(addressIds);


        Order order = new Order();
        order.setId(id);
        order.setOrderDate(DateUtils.parseString2Date(orderDate));
        order.setOrderStatus(orderStatus);
        order.setOrderType(orderType);
        order.setSetmealId(setmealIds);
        order.setAddress(address);//地址信息
        orderSettingListMapper.edit(order);


        //map2 存放order_id address_id
        Integer order_id = order.getId();
        int orderAndAddress = orderSettingListMapper.findOrderAndAddress(order_id);
        //判断该订单有没有填写过地址
        if (orderAndAddress == 0){
            //如果有,就加关联表
            Map map2 = new HashMap();
            map2.put("order_id", order_id);
            map2.put("address_id", addressIds);
            //添加关联表信息
            orderSettingListMapper.addAddressAssociation(map2);
        }
        if (orderAndAddress != 0){
            //如果没有,就修改关联表
            Map map3 = new HashMap();
            map3.put("order_id",order_id);
            map3.put("addressIds",addressIds);
            orderSettingListMapper.editOrderAndAddress(map3);
        }

    }

    /**
     * 查询所有的地址,回显
     */
    @Override
    public List<Address> findAllAddress() {
        return orderSettingListMapper.findAllAddress();
    }

    /**
     * 根据预约id查询地址
     */
    @Override
    public List<Integer> findAddressIdByOrderId(int id) {
        return orderSettingListMapper.findAddressIdByOrderId(id);
    }

    /**
     *删除
     */
    @Override
    public void delete(int id) {
        //先通过id查询关联表中对应的地址id
        int isHaveAddress = orderSettingListMapper.findOrderAndAddress(id);
        if (isHaveAddress !=0){
            //删除关联表
            orderSettingListMapper.deleteById(id);
        }
        //通过id查询是否有健康干预对应
        int isHaveInfo= orderSettingListMapper.CountInterventionId(id);
        if (isHaveInfo !=0){
            //查询健康干预的id
            int InfoId = orderSettingListMapper.findInterventionId(id);
            //删除关联表
            orderSettingListMapper.deleteInfoById(InfoId);
        }
        //删除order表数据
        orderSettingListMapper.delete(id);
    }



}
